package com.minggo.charmword.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;

/**
 * 延迟加载数据的和取消异步任务的父类
 * 
 * @author minggo
 * @date 2014-9-19 上午11:49:44
 */
public abstract class BaseFragment extends ProgressFragment {

	private boolean isInit; // 是否可以开始加载数据
	private boolean isCreated;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		isCreated = true;

	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		isInit = true;
		// System.out.println("父类onViewCreated调用了--->");
	}

	@Override
	public void onResume() {
		super.onResume();
		// System.out.println("父类的onresume调用了");
		if (getUserVisibleHint()) {
			if (isInit && isCreated) {
				isInit = false;// 加载数据完成
				System.out.println("应该去加载数据了");
				showData();
			}
		}
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		// 每次切换fragment时调用的方法
		if (isVisibleToUser) {
			if (isInit && isCreated) {
				isInit = false;// 加载数据完成
				System.out.println("应该去加载数据了");
				showData();
			}
		}
	}

	/**
	 * 取消指定异步任务
	 * 
	 * @param asyncTasks
	 */
	protected void cancelAsyncTask(AsyncTask<?, ?, ?>... asyncTasks) {
		for (AsyncTask<?, ?, ?> asyncTask : asyncTasks) {
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
	}

	protected abstract void showData();

}
